%% estimaStates 
% 
%
% Edited TM: 8/8/2014
% The subittle on the graph for the Innovations was awful.  I have changed
% it so that it now just lists the model, prior, and run.
cd(cucd); 

%% 1. Kalman filter and State decomposition 

%% Old syntaxis 
% [KFStru,logL]=feval(@kfilterNSplits,model.param,model.handle,dataStru.data,...
%     dataStru.trainVec,model.solveOptions,model.model.addsol); 

%% New syntaxis 
%% Allows compatibility with passing initial state and variance 

[KFStru,logL]=feval(filterStru.funcKfilter,model.param,model,dataStru,flags,filterStru);  
cd(location.savePath);
save workspace;

% figNomShares = plotNominalShares(KFStru,model,dataStru,names);
% 
% print(figNomShares,'-dpsc','modelNominalShares')


KFLast.aZero=KFStru.aLast;
KFLast.pZero=KFStru.pLast;
KFLast.aZeroDecomp=squeeze(KFStru.countSt(end,:,:));
save KFLast KFLast;
disp('Saved KFLast with aZero,pZero and aZeroDecomp');
clear KFLast;
cd(cucd);

%% EViews
% Creates a decomposition for a given state in Eviews format and saves to
% an excel file.
cd(location.savePath);

if exist('eviewsReport','var')
    if ~isempty(eviewsReport.states)
        eviewsReport.position = cellposition(eviewsReport.states,names.states);
        eviewsReport.body = KFStru.smoothSt(:,eviewsReport.position);
        xlswrite('EViews',crtcellEViews(eviewsReport.body,sampleStru.cell,...
            eviewsReport.states,eviewsReport.names,{'Smooth States'}),'smooth States');
    end
else
    disp('No EViews Report Requested, Skipping')
end

%% 7. Table with States and Innovations in Filter 
cd(location.savePath);
if isunix==0
    xlswrite('Filter',crtcell(corrcoef(KFStru.innovations),names.shocks,names.shocks,...
        {'Correlation'}),'correlation Innovations');
    xlswrite('Filter',crtcell(KFStru.filteredSt,sampleStru.cell,names.states,...
        {'Smooth States'}),'filtered States');
        xlswrite('Filter',crtcell(KFStru.smoothSt,sampleStru.cell,names.states,...
        {'Smooth States'}),'smooth States');

    xlswrite('Filter',crtcell(KFStru.innovations,sampleStru.cell,names.shocks,...
        {'Smooth Innovations'}),'innovations');
else 
    savecell( crtcell(corrcoef(KFStru.innovations),names.shocks,names.shocks,...
        {'Correlation'}),[],location.savePath,'Filter Correlation'); 
    savecell( crtcell(KFStru.smoothSt,sampleStru.cell,names.states,...
        {'Smooth States'}),[],location.savePath,'Filter States'); 
    savecell(crtcell(KFStru.innovations,sampleStru.cell,nameStru.names.shocks,...
        {'Smooth Innovations'}),[],location.savePath,'Filter Innovations');
end 
% %% Forecasts
% forcStru.endForc = 2018.75; % end date for forecasts
% forecastScript;
% 
% %% Conditional Kiley Decompositions
% % Computes the conditional Kiley Decompositions
% decompSettings;
% 
% for i = 1:length(groupStruct)
%     conditionalForecastDecompositionClean(names,sampleStru,histStru,groupStruct{i},KFStru,forcStru,stateStruct,model,i)
% end
% %% Forecast ahead decompositions
% % Uses the states, decomposed by shocks to obtain forecasts specific to
% % observing a specified group of shocks
% for i = 1:length(groupStruct)
%     [forecast.allShocksOff, forecastConditional] = obtainConditionalForecasts(names,sampleStru,histStru,groupStruct,KFStru,forcStru,model,i);
% end
% 
% %% Conditional Forecast Plotting
% % Plots the conditional forecasts created above
% plotConditionalForecasts(sampleStru,model,forcStru,forecast,histStru,forecastConditional)

% % plot forecasts 
% fplot(sampleStru,forecast,forc);

%%
cd(cucd);
disp('Turn me into a TEX Table');

%% 2. Decomposition for the Observables 
names.obsNames=names.observables; 
names.stateNames=names.states; 

%% 2.a Grouped by Observables, that shock Only
clear inStru
inStru.caseDecomp='single'; 
inStru.orgBy='series'; 
graphMat=DecompSeries(dataStru.data,model.handle,model.param,model.solveOptions,...
    model.addsol,inStru,KFStru,sampleStru,[],names); 
compileGraphsPDF(graphMat,'Obs Dec by Series',location.savePath); 
close all; 

%% 2.b Grouped by Shocks, that shock Only 
inStru.caseDecomp='single'; 
inStru.orgBy='shocks'; 
graphMat=DecompSeries(dataStru.data,model.handle,model.param,model.solveOptions,model.addsol,inStru,KFStru,sampleStru,[],names); 
compileGraphsPDF(graphMat,'Obs Dec by Shocks',location.savePath); 
close all; 

%% 2.c Excluding that Shock 
inStru.caseDecomp='except'; 
inStru.orgBy='shocks'; 
graphMat=DecompSeries(dataStru.data,model.handle,model.param,model.solveOptions,model.addsol,inStru,KFStru,sampleStru,[],names); 
compileGraphsPDF(graphMat,'Obs Dec Except',location.savePath); 
close all; 

%% 2.d Contribution of Shocks 
clear inStru
inStru.caseDecomp='single';
inStru.orgBy='shocks';
inStru.extract=names.observables;
graphMat=shockContributions(inStru,KFStru,sampleStru,[],names);
compileGraphsPDF(graphMat,'Obs Contrib',location.savePath);
close all; 

%% 2.e Custom Shocks
clear inStru
close all
inStru.caseDecomp   = 'custom';
inStru.orgBy        = 'shocks';
inStru.GraphTitle   = 'Sum of ';
% inStru.ShockSum     = names.shockNames;
inStru.ShockSum     = {'Labor Disutility' 'ISTS' 'Permanent Neutral'};
for i = 1:numel(inStru.ShockSum)
    inStru.GraphTitle = [inStru.GraphTitle inStru.ShockSum{i} ', '];
end
inStru.GraphTitle = inStru.GraphTitle(1:end-2);


inStru.override     = 1;
graphMat=DecompSeries(dataStru.data,model.handle,model.param,model.solveOptions,...
    model.addsol,inStru,KFStru,sampleStru,[],names); 


%% 3.Decomposition for states, grouped by Observables
if isfield(report,'stateDecomp')==true && isempty(report.stateDecomp)==false
    flags.stateDecomp=1; 
    %% 3.a Grouped by Observables, that shock Only
    clear inStru
    inStru.caseDecomp='single';
    inStru.orgBy='series';
    inStru.extract=report.stateDecomp; 
    graphMat=DecompSeries([],model.handle,model.param,model.solveOptions,model.addsol,inStru,KFStru,sampleStru,[],names);
    compileGraphsPDF(graphMat,'States Dec by Series',location.savePath);
    close all;
    %% 3.b Excluding that Shock 
    inStru.caseDecomp='except';
    inStru.orgBy='shocks';
    graphMat=DecompSeries([],model.handle,model.param,model.solveOptions,model.addsol,inStru,KFStru,sampleStru,[],names);
    compileGraphsPDF(graphMat,'State Dec Except',location.savePath);
    close all; 
    %% 3.c Contribution of Shocks 
    inStru.caseDecomp='single';
    inStru.orgBy='shocks';
        inStru.extract=report.stateDecomp; 

    graphMat=shockContributions(inStru,KFStru,sampleStru,[],names);
    compileGraphsPDF(graphMat,'State Contrib',location.savePath);
    close all;
else 
    flags.stateDecomp=0; 
end 

%% 4. Plot of Innovations 
names.colNames=names.shocks; 
clear graphStru; 
graphStru.suptitle='Innovations'; 
% Create Subtitle (TM: 8/8/2014)
    slashloc        = regexp(location.savePath,'\','split');
    fixtexsettings.type = 'file'; 
    graphStru.subtitle = tex2string(slashloc(end-2:end),fixtexsettings)';
graphStru.subtitleFontSize=9; 
handlesInnovations=plotStates(KFStru.innovations,sampleStru,graphStru,names); 
compileGraphsPDF(handlesInnovations,'Innovations',location.savePath); 
clear graphStru handlesInnovations; 

%% 5. Plot of Selected States 
if flags.stateDecomp==true 
    report.stateDecompPos=cellposition(report.stateDecomp,names.states); 
    clear graphStru;
    graphStru.suptitle='Smooth States';
    graphStru.subtitle=[];
    graphStru.subtitleFontSize=9;
    %graphStru.extract=report.stateDecomp; 
    names.colNames=report.stateDecomp;
    tempMat=KFStru.smoothSt(:,report.stateDecompPos);
    handlesStates=plotStates(tempMat,sampleStru,graphStru,names);
    compileGraphsPDF(handlesStates,'States',location.savePath); 
    clear graphStru handlesStates;
end 

%% 6. Decomposition of observables for selected subsamples
if isfield(report,'subSamples')==true && isempty(report.subSamples)==false
    %flags.subSamples=1;
    report.sampleVec=sampleStru.vector;
    printcell(report.subSamples);
    report=sampleAssignments(report,1);

    NSub=size(report.subSamples,1);
    clear inStru
    inStru.caseDecomp='single';
    for ii=1:NSub
        tempPos=(report.subSamplePos(ii,1):report.subSamplePos(ii,2));
        %         tempKFStru.countObs=KFStru.countObs(tempPos,:,:);
        %         tempKFStru.countSt=KFStru.countSt(tempPos,:,:);
        %        tempSampleStru.sampleVec=sampleStru.sampleVec(tempPos);
        tempString={[char(report.subSamples(ii,1)),' ',char(report.subSamples(ii,2))]};
        tempString=regexprep(tempString,'-','_');
        %% 6.a Grouped by Observables, that shock Only
        inStru.orgBy='series';
        inStru.caseDecomp='single';
        inStru.samplePos=tempPos; 
        graphMat=DecompSeries(dataStru.data,model.handle,model.param,model.solveOptions,model.addsol,...
            inStru,KFStru,sampleStru,[],names);
        tempFileName=['Obs Dec ',char(tempString)];
        compileGraphsPDF(graphMat,tempFileName,location.savePath);
        clear graphMat
        close all;
        %% 6.b Exclude, by Shocks
        inStru.orgBy='shocks';
        inStru.caseDecomp='except';
        graphMat=DecompSeries(dataStru.data,model.handle,model.param,model.solveOptions,model.addsol,...
            inStru,KFStru,sampleStru,[],names);
        tempFileName=['Obs Except ',char(tempString)];
        compileGraphsPDF(graphMat,tempFileName,location.savePath);
        clear graphMat
        close all;
        %% 6.c Contributions
        
        inStru.caseDecomp='single';
        inStru.orgBy='shocks';
        inStru.extract=names.observables;
        graphMat=shockContributions(inStru,KFStru,sampleStru,[],names);
        tempFileName=['Obs Contrib ',char(tempString)];
        compileGraphsPDF(graphMat,tempFileName,location.savePath);
        
        %%
        if flags.stateDecomp==true
            %% 6.d Grouped by States, that shock Only
            inStru.caseDecomp='single';
            inStru.orgBy='series';
            inStru.extract=report.stateDecomp;
            tempKFStru.countSt=KFStru.countSt(tempPos,:,:);
            tempFileName=['States Dec ',char(tempString)];
            graphMat=DecompSeries([],model.handle,model.param,...
                model.solveOptions,model.addsol,inStru,KFStru,...
                sampleStru,[],names);
            compileGraphsPDF(graphMat,tempFileName,location.savePath);
            close all;
            
            inStru.caseDecomp='single';
            inStru.orgBy='shocks';
            inStru.extract=report.stateDecomp;
            graphMat=shockContributions(inStru,KFStru,sampleStru,[],names);
            tempFileName=['States Contrib ',char(tempString)];
            compileGraphsPDF(graphMat,tempFileName,location.savePath);
            close all;
                                   
        end
    end
else
    flags.subSamples=0;
end
clear graphMat inStru temp* NSub; 

